package ar.edu.unlp.info.cdiv.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import ar.edu.unlp.info.cdiv.Constants;
import ar.edu.unlp.info.cdiv.ToWebPConverter;
import ar.edu.unlp.info.cdiv.model.Album;
import ar.edu.unlp.info.cdiv.model.Persona;
import ar.edu.unlp.info.cdiv.model.User;
import ar.edu.unlp.info.cdiv.service.PersonService;

@Controller
@RequestMapping(value = "perfil")
public class PersonController extends AbstractController{
	
	private static Logger logger = Logger.getLogger(PersonController.class);
	
	@Autowired
	PersonService service;
	
	@Autowired
	ToWebPConverter converter;
	
	@RequestMapping(value = "guardar", method = RequestMethod.POST)
	public String register(Model model,@RequestParam String nombre, @RequestParam String apellido, @RequestParam String biografia, @RequestParam MultipartFile file,@RequestParam String usuario,@RequestParam String password, @RequestParam String password2) throws IOException {
		User user = new User(usuario, password);
		Persona persona = new Persona(nombre, apellido, biografia, user);
		service.save(persona);
		String folder = this.getTemporalFolder() + File.separator+usuario;
		File dir = new File(folder);
		FileUtils.forceMkdir(dir);
		String filename = folder+File.separator+"foto"+ file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
		FileOutputStream fileOut = new FileOutputStream(filename);
		fileOut.write(file.getBytes());
		fileOut.flush();
		fileOut.close();
		
		String folderResul = this.getWebpFolder()+ File.separator+usuario;
		File dirResul = new File(folderResul);
		FileUtils.forceMkdir(dirResul);
		String filenameResul = folderResul+File.separator+"foto.webp";
		converter.convert2wbp(filename, filenameResul);
		FileOutputStream fileOutResul = new FileOutputStream(filenameResul);
		fileOutResul.write(file.getBytes());
		fileOutResul.flush();
		fileOutResul.close();
		
		
		
		model.addAttribute(Constants.CURRENT_USER,persona);
		return "redirect:/perfil/"+persona.getId()+"/"+persona.getUser().getUsername()+"/albums";
	}
	
	@RequestMapping(value = "{id}/subirFoto", method = RequestMethod.POST)
	public String subirFoto(ModelMap model,@PathVariable Long id, @RequestParam MultipartFile file,HttpServletRequest request) throws IOException {
		Album album = (Album)service.get(Album.class, id);
		Persona persona = (Persona) request.getSession().getAttribute(Constants.CURRENT_USER);
		String sourceFolder = this.getTemporalFolder() + File.separator+ persona.getUser().getUsername() + File.separator+album.getNombre();
		File dir = new File(sourceFolder);
		FileUtils.forceMkdir(dir);
		String source = sourceFolder+File.separator+file.getOriginalFilename();
		FileOutputStream fileOut = new FileOutputStream(source);
		fileOut.write(file.getBytes());
		fileOut.flush();
		fileOut.close();

		
		String filename = file.getOriginalFilename();
		String fileExtension = filename.substring(filename.lastIndexOf(".")+1);
		String resultFolder = this.getWebpFolder() + File.separator+ persona.getUser().getUsername() + File.separator+album.getNombre();
		File dirResult = new File(resultFolder);
		FileUtils.forceMkdir(dirResult);
		
		String result = resultFolder + File.separator + filename.replace(fileExtension, Constants.WEBP_EXTENSION);
		converter.convert2wbp(source, result);

		fileOut = new FileOutputStream(result);
		fileOut.write(file.getBytes());
		fileOut.flush();
		fileOut.close();
		
		album.add(filename.replace(fileExtension, Constants.WEBP_EXTENSION));
		service.save(album);
		model.addAttribute("album",album);
		File fileIn = new File(source);
		File fileO = new File(result);		
		logger.info("Comprimiendo el archivo '"+source+"' de "+fileIn.length()+" bytes a "+fileO.length()+" bytes.");
		return "redirect:/perfil/"+persona.getId()+"/"+persona.getUser().getUsername()+"/album/"+album.getId()+"/"+album.getNombre();
	}
	



	@RequestMapping(value = "view", method = RequestMethod.GET)
	public String viewUpload() {
		return "file-upload";
	}
	
	protected Persona getProfilePerson(){
		User user = new User("jperez", "jperez");
		Persona person = new Persona("Juan", "Perez", "soy una persona copada", user );
		return person;
	}
	
	@Deprecated
	@RequestMapping("{id}/{username}")
	public ModelAndView viewProfile(@PathVariable Long id, @PathVariable String username){
		ModelAndView mav = new ModelAndView();
		mav.addObject("profile", service.get(Persona.class, id));
		mav.setViewName("persona/ficha-persona");
		return mav;
	}
	
	@RequestMapping("{id}/{usuario}/albums")
	public ModelAndView viewAlbums(@PathVariable Long id, @PathVariable String usuario){
		Persona persona = (Persona) service.get(Persona.class, id);
		ModelAndView mav = new ModelAndView("persona/albums");
		mav.addObject(Constants.PERSONA,persona);
		mav.addObject("albums",persona.getAlbums());
		mav.addObject(Constants.PERFIL_VISITADO,persona);
		return mav;
	}
	
	@RequestMapping("subir")
	public String newAlbum(HttpServletRequest request){
		request.getSession().setAttribute(Constants.SECCION,Constants.SUBIR);
		return "persona/subir";
	}
	
	@RequestMapping(value = "guardarAlbum",method = RequestMethod.POST)
	public String guardarAlbum(ModelMap model, @RequestParam String nombreAlbum, HttpServletRequest request){
		Persona persona = (Persona)request.getSession().getAttribute(Constants.CURRENT_USER);
		Album album = new Album(nombreAlbum, new Date(),persona);
		persona.add(album);
		service.save(persona);
		return "redirect:/perfil/"+persona.getId()+"/"+persona.getUser().getUsername()+"/albums";
	}
	
	@RequestMapping (value = "{id_usuario}/{usuario}/album/{id_album}/{album}", method = RequestMethod.GET)
	public String verAlbum(Model model, @PathVariable Long id_usuario, @PathVariable String usuario, @PathVariable Long id_album, @PathVariable String album){
		Album anAlbum = (Album)service.get(Album.class, id_album);
		Persona persona = (Persona)service.get(Persona.class, id_usuario);
		model.addAttribute("album",anAlbum);
		model.addAttribute(Constants.PERSONA, persona);
		return "persona/album";
	}
}